/*!
 * \file ParserCTP.h
 * \project	WonderTrader
 *
 * \author Wesley
 * \date 2020/03/30
 *
 * \brief
 */
#pragma once
#include "../Includes/IParserApi.h"
#include "../Share/DLLHelper.hpp"
#include "CTP6.3.15/ThostFtdcMdApi.h"
#include <map>

NS_WTP_BEGIN
class WTSTickData;
NS_WTP_END

USING_NS_WTP;

class ParserCTP : public IParserApi, public CThostFtdcMdSpi {
public:
    ParserCTP();
    virtual ~ParserCTP();

public:
    enum LoginStatus { LS_NOTLOGIN, LS_LOGINING, LS_LOGINED };

    // IQuoteParser 接口
public:
    virtual bool init(WTSVariant* config) override;

    virtual void release() override;

    virtual bool connect() override;

    virtual bool disconnect() override;

    virtual bool isConnected() override;

    virtual void subscribe(const CodeSet& vecSymbols) override;
    virtual void unsubscribe(const CodeSet& vecSymbols) override;

    virtual void registerSpi(IParserSpi* listener) override;

    // CThostFtdcMdSpi 接口
public:
    virtual void OnRspError(CThostFtdcRspInfoField* pRspInfo, int nRequestID,
                            bool bIsLast);

    virtual void OnFrontConnected();

    virtual void OnRspUserLogin(CThostFtdcRspUserLoginField* pRspUserLogin,
                                CThostFtdcRspInfoField* pRspInfo,
                                int nRequestID, bool bIsLast);

    ///登出请求响应
    virtual void OnRspUserLogout(CThostFtdcUserLogoutField* pUserLogout,
                                 CThostFtdcRspInfoField* pRspInfo,
                                 int nRequestID, bool bIsLast);

    virtual void OnFrontDisconnected(int nReason);

    virtual void
    OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField* pSpecificInstrument,
                         CThostFtdcRspInfoField* pRspInfo, int nRequestID,
                         bool bIsLast);

    virtual void
    OnRtnDepthMarketData(CThostFtdcDepthMarketDataField* pDepthMarketData);

    virtual void
    OnRspSubMarketData(CThostFtdcSpecificInstrumentField* pSpecificInstrument,
                       CThostFtdcRspInfoField* pRspInfo, int nRequestID,
                       bool bIsLast);

    virtual void OnHeartBeatWarning(int nTimeLapse);

private:
    /*
     *	发送登录请求
     */
    void ReqUserLogin();
    /*
     *	订阅品种行情
     */
    void DoSubscribeMD();
    /*
     *	检查错误信息
     */
    bool IsErrorRspInfo(CThostFtdcRspInfoField* pRspInfo);

private:
    uint32_t m_uTradingDate;
    CThostFtdcMdApi* m_pUserAPI;

    std::string m_strFrontAddr;
    std::string m_strBroker;
    std::string m_strUserID;
    std::string m_strPassword;
    std::string m_strFlowDir;
    bool m_bLocaltime; //是否使用本地时间戳

    CodeSet m_filterSubs;

    int m_iRequestID;

    IParserSpi* m_sink;
    IBaseDataMgr* m_pBaseDataMgr;

    DllHandle m_hInstCTP;
    typedef CThostFtdcMdApi* (*CTPCreator)(const char*, const bool, const bool);
    CTPCreator m_funcCreator;
};
